package com.learn.edugatewayboot.filter;

import com.learn.edugatewayboot.config.GatewayConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 对所有请求进行拦截，放行登录成功的请求
 */
@Slf4j
@Component
public class Oauth2AuthenticationFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GatewayConfig gatewayConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行不拦截的请求
        List<String> whiteList = gatewayConfig.getWhiteList();
        for (String str : whiteList) {
            if(str.endsWith("*")){
                str = str.replace("*","");
                if(request.getURI().getPath().contains(str)){
                    log.info("放行 {}",request.getURI().getPath());
                    return chain.filter(exchange);
                }
            }else if (request.getURI().getPath().endsWith(str)) {
                log.info("放行 {}",request.getURI().getPath());
                return chain.filter(exchange);
            }
        }
        log.info("拦截URI：{}",request.getURI().getPath());
        //判断cookie中是否有jti
        String jti = null;
        HttpCookie httpCookie = request.getCookies().getFirst("uid");
        if (httpCookie != null){
            jti = httpCookie.getValue();
        }
        if (StringUtils.isEmpty(jti)){
            //拒绝访问,请求跳转
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断redis中token是否存在
        String redisToken = stringRedisTemplate.boundValueOps(jti).get();
        if (StringUtils.isEmpty(redisToken)){
            //拒绝访问，请求跳转
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验通过,请求头增强，加入Token，交给资源服务验证
        request.mutate().header("Authorization","Bearer "+redisToken);
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
